package com.moli.iov.manager.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.iov.cache.RedisUtil;
import com.moli.iov.manager.ManagerConstant;
import com.moli.iov.manager.activemq.ActiveMQProducer;
import com.moli.iov.manager.enums.UserStatusEnum;
import com.moli.iov.manager.mapper.AuthoritySysUserMapper;
import com.moli.iov.manager.model.dto.AuthoritySysUserQueryDto;
import com.moli.iov.manager.model.po.AuthorityRole;
import com.moli.iov.manager.model.po.AuthoritySysUser;
import com.moli.iov.manager.service.IAuthoritySysUserService;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.Md5PwdEncoder;
import com.moli.iov.util.NumberUtil;
import com.moli.iov.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sy
 * @since 2018-12-13
 */
@Slf4j
@Service("iAuthoritySysUserService")
public class AuthoritySysUserServiceImpl extends ServiceImpl<AuthoritySysUserMapper, AuthoritySysUser> implements IAuthoritySysUserService {


    @Autowired
    private AuthoritySysUserMapper authoritySysUserMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ActiveMQProducer activeMQProducer;

    @Override
    public RestResponse saveUser(AuthoritySysUser authoritySysUser) {
        if (authoritySysUser == null) {
            log.error(ManagerConstant.ADD_FAILED_MSG + ",参数为空");
            return RestResponse.failure(ManagerConstant.ADD_FAILED_MSG);
        }
        String account = authoritySysUser.getAccount();
        String password = authoritySysUser.getPassword();
        if (!StringUtil.isBlank(password) && !StringUtil.isBlank(account)) {//为空不修改密码
            String encodePassword = Md5PwdEncoder.encodePassword(password, account);
            authoritySysUser.setPassword(encodePassword);
        }
        boolean result = saveOrUpdate(authoritySysUser);
        Date disableTime = authoritySysUser.getDisableTime();
        long currentTimeMillis = System.currentTimeMillis();
        //新建的时候就指定自动过期时间
        if (result && disableTime != null && disableTime.getTime() > currentTimeMillis) {
            AuthoritySysUser authoritySysUser2 = new AuthoritySysUser();
            authoritySysUser2.setId(authoritySysUser.getId());
            authoritySysUser2.setStatus(1);
            authoritySysUser2.setDisableTime(disableTime);
            long diff = disableTime.getTime() - currentTimeMillis;
            activeMQProducer.send(authoritySysUser2, diff);
        }
        return result ? RestResponse.success(ManagerConstant.ADD_SUCCESS_MSG,null) : RestResponse.failure(ManagerConstant.ADD_FAILED_MSG);
    }

    @Override
    public RestResponse updateUser(AuthoritySysUser authoritySysUser) {
        if (authoritySysUser == null || authoritySysUser.getId() == null) {
            log.error(ManagerConstant.UPDATE_FAILED_MSG + ",参数为空");
            return RestResponse.failure(ManagerConstant.UPDATE_FAILED_MSG);
        }
        String account = authoritySysUser.getAccount();
        String password = authoritySysUser.getPassword();
        Long id = authoritySysUser.getId();
        Integer status = authoritySysUser.getStatus();
        Date disableTime = authoritySysUser.getDisableTime();
        if (!StringUtil.isBlank(password) && !StringUtil.isBlank(account)) {//为空不修改密码
            String encodePassword = Md5PwdEncoder.encodePassword(password, account);
            authoritySysUser.setPassword(encodePassword);
        }
        long timeMillis = System.currentTimeMillis();
        AuthoritySysUser authoritySysUser1 = new AuthoritySysUser();
        //用户设置的停用时间小于现在时间，立即设置停用
        if (id != null && status != null && status == 0
                && disableTime != null
                && disableTime.getTime() < timeMillis) {
            authoritySysUser1.setId(id);
            authoritySysUser1.setStatus(1);
            authoritySysUser1.setDisableTime(disableTime);
        }
        int ret = authoritySysUserMapper.updateUser(authoritySysUser);
        if (ret == 0) {
            return RestResponse.failure(ManagerConstant.UPDATE_FAILED_MSG);
        }
        //用户设置的停用时间大于现在时间，延时停用
        if (ret == 0 && id != null && status != null
                && status == 0 && disableTime != null
                && disableTime.getTime() > timeMillis) {
            authoritySysUser1.setId(id);
            authoritySysUser.setDisableTime(disableTime);
            authoritySysUser1.setStatus(1);
            activeMQProducer.send(authoritySysUser1, (disableTime.getTime()) - timeMillis);
        }
        return RestResponse.success(ManagerConstant.UPDATE_SUCCESS_MSG,null);
    }


    @Override
    public RestResponse queryUserById(long id) {
        AuthoritySysUser sysUser = authoritySysUserMapper.queryUserByid(id);
        return RestResponse.success(sysUser);
    }

    @Override
    public IPage<AuthoritySysUser> querySysUserByPage(AuthoritySysUserQueryDto authoritySysUserQueryDto) {

        Page<AuthoritySysUser> userPage = new Page<>();
        if (authoritySysUserQueryDto == null) {
            return userPage;
        }
        QueryWrapper<AuthoritySysUser> queryWrapper = new QueryWrapper<AuthoritySysUser>();
        if (StringUtil.isNotBlank(authoritySysUserQueryDto.getAccount())) {
            queryWrapper.like("account", authoritySysUserQueryDto.getAccount());
        }
        if (StringUtil.isNotBlank(authoritySysUserQueryDto.getUserName())) {
            queryWrapper.like("user_name", authoritySysUserQueryDto.getUserName());
        }
        if (authoritySysUserQueryDto.getStatus() != null) {
            queryWrapper.eq("status", authoritySysUserQueryDto.getStatus());
        }
        //只查询未删除的角色信息
        queryWrapper.eq("is_delete", 0);
        long count = count(queryWrapper);
        userPage.setTotal(count);
        Long pageNum = authoritySysUserQueryDto.getPageNum();
        Long pageSize = authoritySysUserQueryDto.getPageSize();
        long index = (pageNum - 1) * pageSize;
        long totalPage = (count % pageSize) == 0 ? count % pageSize : count % pageSize + 1;
        userPage.setPages(totalPage);//总页数
        userPage.setCurrent(authoritySysUserQueryDto.getPageNum());
        List<AuthoritySysUser> authoritySysUsers = authoritySysUserMapper.querySysUser(index, authoritySysUserQueryDto);
        userPage.setRecords(authoritySysUsers);
//        IPage<AuthoritySysUser> page = this.page(new Page<AuthorityRole>(authoritySysUserQueryDto.getPageNum(), authoritySysUserQueryDto.getPageSize()), queryWrapper);
        return userPage;

    }

    /**
     * 根据账户查询
     *
     * @param authoritySysUserQueryDto
     * @return
     */
    @Override
    public RestResponse<AuthoritySysUser> getUserByAccount(AuthoritySysUserQueryDto authoritySysUserQueryDto, int status) {
        if (authoritySysUserQueryDto == null || StringUtil.isBlank(authoritySysUserQueryDto.getAccount())) {
            return RestResponse.failure("账户不能为空");
        }
        QueryWrapper<AuthoritySysUser> queryWrapper = new QueryWrapper<AuthoritySysUser>();
        queryWrapper.eq("account", authoritySysUserQueryDto.getAccount());
        if (status != 2) {
            queryWrapper.eq("status", status);
        }
        queryWrapper.eq("is_delete", 0);
        AuthoritySysUser authoraitySysUser = super.getOne(queryWrapper, false);
        return authoraitySysUser == null ? RestResponse.failure("账户不存在") : RestResponse.success(authoraitySysUser);
    }


//    /**
//     * 根据账户查询
//     *
//     * @param authoritySysUserQueryDto
//     * @return
//     */
//    @Override
//    public RestResponse<AuthoritySysUser> getUserByAccount(AuthoritySysUserQueryDto authoritySysUserQueryDto) {
//        if (authoritySysUserQueryDto == null || StringUtil.isBlank(authoritySysUserQueryDto.getAccount())) {
//            return RestResponse.failure("账户不能为空");
//        }
//        QueryWrapper<AuthoritySysUser> queryWrapper = new QueryWrapper<AuthoritySysUser>();
//        queryWrapper.eq("account", authoritySysUserQueryDto.getAccount());
//        queryWrapper.eq("status", UserStatusEnum.ENABLE.flag);
//        AuthoritySysUser authoraitySysUser = super.getOne(queryWrapper, false);
//        return authoraitySysUser == null ? RestResponse.failure("账户不存在") : RestResponse.success(authoraitySysUser);
//    }

    @Override
    public void setUserAuthCache(Long userId) {
        redisUtil.set(ManagerConstant.USER_AUTH_TAG_PREFIX + userId, userId + "");
    }

    @Override
    public String getUserAuthCache(Long userId) {
        return redisUtil.get(ManagerConstant.USER_AUTH_TAG_PREFIX + userId);
    }

    @Override
    public void clearUserAuthCache(Long userId) {
        redisUtil.delete(ManagerConstant.USER_AUTH_TAG_PREFIX + userId);
    }

    @Override
    public List<AuthoritySysUser> getUsersByRoleId(Long roleId) {
        return authoritySysUserMapper.getUsersByRoleId(roleId);
    }

    @Override
    public void clearUserAuthCacheByRoleId(Long roleId) {
        List<AuthoritySysUser> userList = getUsersByRoleId(roleId);
        if (userList != null && userList.size() > 0) {
            for (AuthoritySysUser authoritySysUser : userList) {
                Long sysUserId = authoritySysUser.getId();
                clearUserAuthCache(sysUserId);
            }
        }
    }

//    @Override
//    public void updateUsersBatch(List<AuthoritySysUser> authoritySysUsers) {
//        saveBatch(authoritySysUsers);
//    }

    @Override
    public RestResponse deleteUser(AuthoritySysUser authoritySysUser) {

        Long userId;
        if (authoritySysUser == null || (userId = authoritySysUser.getId()) == null) {
            log.error("删除失败，参数有误");
            return RestResponse.failure(ManagerConstant.DELETE_FAILED_MSG);
        }

        AuthoritySysUser sysUser = getById(userId);
        if (sysUser == null || sysUser.getIsDelete() == 1) {
            log.error("删除失败，改用户不存在");
            return RestResponse.failure(ManagerConstant.DELETE_FAILED_MSG);
        }
        Integer status = sysUser.getStatus();
        if (status != 1) {
            log.error("删除失败，只有停用的用户才能被删除");
            return RestResponse.failure(ManagerConstant.DELETE_FAILED_MSG);
        }
        authoritySysUser.setIsDelete(1);
        saveOrUpdate(authoritySysUser);
        return RestResponse.success(ManagerConstant.DELETE_SUCCESS_MSG,null);
    }

    @Override
    public List<AuthoritySysUser> getExpiringUsers() {
        List<AuthoritySysUser> expiringUsers = authoritySysUserMapper.getExpiringUsers();
        return expiringUsers;
    }


}
